import xbmc, xbmcgui, xbmcplugin, urllib2, urllib, re, sys, os, time, traceback
 
import tv4parser
import utility 
from utility import ContentFactory

rootDir = os.getcwd()
if rootDir[-1] == ';':rootDir = rootDir[0:-1]

class PluginRunner:
    def __init__(self):
        self.progressDialog = None
        self.run()        
    
    def play(self, url, name, thumb, studio, plot, genre):    
        """ Play in XBMC """
        if not thumb: thumb = ""
        if not studio: studio = ""
        if not plot: plot = ""
        if not genre: genre = ""
        
        item=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=thumb)
        
        item.setInfo( type="Video", 
                      infoLabels={ "Title": name } #, "Studio": studio, "Plot": plot, "Genre": genre 
                    )
        
        try:        
            player = xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER)            
            player.play(url, item)
        except:
            dialog = xbmcgui.Dialog()
            dialog.ok("Error", "Unable to play video!")
        

    def addListItem(self, title, uri, icon=None, thumb=None, folder=True):
        """ Adds a list item to folder view """
        
        if not icon:
            if folder:  icon = "DefaultFolder.png"
            else:       icon = "DefaultVideo.png"
            
        if not thumb: thumb = ""
        
        url = "%s?%s" % (sys.argv[0], uri)
        li = xbmcgui.ListItem(title, iconImage=icon, thumbnailImage=thumb)
        
        li.setInfo(type="Video", 
                   infoLabels={ "Title": title }
                   )
        
        return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=folder)
            
    def formatExceptionInfo(self, level = 6):
        error_type, error_value, trbk = sys.exc_info()
        tb_list = traceback.format_tb(trbk, level)    
        s = "Error: %s \nDescription: %s \nTraceback:" % (error_type.__name__, error_value)
        for i in tb_list:
            s += "\n" + i
        return s
    
    def writeErrorLog(self):
        xbmc.log( "     ** Error in sweplay addon: **\r\n%s" % ( self.formatExceptionInfo() ), xbmc.LOGERROR )
        
    def onProgress(self, sender, value, text1=None):
        """ Update progress bar """    
        if self.progressDialog:
            self.progressDialog.update(value, text1)
        
            if self.progressDialog.iscanceled():
                raise utility.UserCanceledError()
    
    def onItemParsed(self, sender, item):
        """ Adds items as they are parsed """
        
        if not item: return
        
        if(type(item) == utility.VideoItem):                        
            self.play(item.URL, item.Title, item.Image, item.Studio, item.Plot, item.Genre)            
        
        elif(type(item) == utility.FolderItem):
            self.addListItem(item.Title, item.URI, thumb=item.Image, folder=True)
            
        elif(type(item) == utility.ImageItem):
            self.addListItem(item.Title, item.URI, thumb=item.Image, folder=False)
        
        elif(type(item) == utility.Item):
            self.addListItem(item.Title, item.URI, folder=False)
            
        else: assert("Item type not supported!")
        

    def downloadData(self):
        """ Downloads data from the mighty web         
        """

        self.progressDialog = xbmcgui.DialogProgress()
        self.progressDialog.create("Download","Getting data from website")    
        
        errorMessage = str()
        results = None

        try:
            parser = ContentFactory.getParser(sys.argv[2])
            parser.ProgressEvent.addListener( self.onProgress )
            parser.ItemAddedEvent.addListener( self.onItemParsed )               
            results = parser.parse()

        #TODO: Modify to catch only relevant errors?!
        except utility.UserCanceledError:
            pass
        except urllib2.URLError, e:
            errorMessage = "There was an error downloading data. Webserver might not be responding, verify your internet connection."
            self.writeErrorLog()
        except Exception, e:
            errorMessage = str(e)
            self.writeErrorLog()

        if errorMessage:    
            dialog = xbmcgui.Dialog()  
            dialog.ok("Error",  errorMessage)
            
        return results
        
    def run(self):
        results = self.downloadData()

        #Don't write end of directory when playing video, but write it if no results at all...
        if not results or ( len(results) > 0 and type(results[0] != utility.VideoItem )):
            xbmcplugin.endOfDirectory(int( sys.argv[1] ), True)
        

#Run the plugin!
PluginRunner()


    
